<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>翻译 - 多语言旅行助手</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="style-translation.css">
    <base href="/">
</head>
<body>
    <!-- 顶部导航栏 -->
    <header>
        <h1>多语言旅行助手</h1>
        <nav>
            <ul>
                <li><a href="index.html">首页</a></li>
                <li><a href="learning.html">学习中心</a></li>
                <li><a href="translation.html" class="active">翻译</a></li>
                <li><a href="culture.html">文化知识库</a></li>
                <li><a href="map.html">离线地图</a></li>
                <li><a href="travel-plan.html">旅行计划</a></li>
                <li><a href="offline-content.html">离线内容</a></li>
                <li><a href="profile.html">个人资料</a></li>
                <li><a href="settings.html">设置</a></li>
            </ul>
        </nav>
    </header>

    <!-- 侧边导航栏 -->
    <aside class="side-nav">
        <ul>
            <li>
                <a href="index.html">
                    <img src="images/home.svg" alt="首页图标">
                    <span>首页</span>
                </a>
            </li>
            <li>
                <a href="learning.html">
                    <img src="images/book-open-bold.svg" alt="学习图标">
                    <span>学习</span>
                </a>
            </li>
            <li>
                <a href="translation.html" class="active">
                    <img src="images/vector_25_310.svg" alt="翻译图标">
                    <span>翻译</span>
                </a>
            </li>
            <li>
                <a href="culture.html">
                    <img src="images/globe-bold.svg" alt="文化图标">
                    <span>文化</span>
                </a>
            </li>
            <li>
                <a href="map.html">
                    <img src="images/vector_25_317.svg" alt="地图图标">
                    <span>地图</span>
                </a>
            </li>
            <li>
                <a href="offline-content.html">
                    <img src="images/vector_25_324.svg" alt="离线内容图标">
                    <span>离线</span>
                </a>
            </li>
            <li>
                <a href="settings.html">
                    <img src="images/vector_25_331.svg" alt="设置图标">
                    <span>设置</span>
                </a>
            </li>
        </ul>
    </aside>

    <!-- 内容区 -->
    <main class="content translation-content">
        <h1 class="page-title">翻译</h1>
        
        <div class="translation-container">
            <div class="translation-box">
                <div class="translation-header">
                    <div class="translation-title">文本翻译</div>
                    <div class="language-selector">
                        <select id="source-language">
                            <option value="auto">自动检测</option>
                            <option value="zh">中文</option>
                            <option value="en">英文</option>
                            <option value="ja">日文</option>
                            <option value="ko">韩文</option>
                            <option value="fr">法文</option>
                            <option value="de">德文</option>
                            <option value="es">西班牙文</option>
                            <option value="it">意大利文</option>
                        </select>
                        <button id="swap-languages" class="swap-btn">
                            <img src="images/swap-icon.svg" alt="交换语言" width="16" height="16">
                        </button>
                        <select id="target-language">
                            <option value="en">英文</option>
                            <option value="zh" selected>中文</option>
                            <option value="ja">日文</option>
                            <option value="ko">韩文</option>
                            <option value="fr">法文</option>
                            <option value="de">德文</option>
                            <option value="es">西班牙文</option>
                            <option value="it">意大利文</option>
                        </select>
                    </div>
                </div>
                
                <textarea id="source-text" class="translation-textarea" placeholder="请输入要翻译的文本"></textarea>
                
                <div class="translation-actions">
                    <div class="action-buttons">
                        <button id="translate-btn" class="primary-btn">翻译</button>
                        <button id="clear-btn" class="secondary-btn">清空</button>
                        <button id="voice-input-btn" class="secondary-btn">
                            <img src="images/placeholder.svg" alt="语音输入" width="16" height="16">
                            语音输入
                        </button>
                    </div>
                    <div class="character-count">0/5000</div>
                </div>
                
                <div id="translation-result" class="translation-result" style="display: none;">
                    <div class="result-header">
                        <div class="result-title">翻译结果</div>
                        <div class="result-actions">
                            <button id="copy-btn" class="secondary-btn">
                                <img src="images/placeholder.svg" alt="复制" width="16" height="16">
                                复制
                            </button>
                            <button id="speak-btn" class="secondary-btn">
                                <img src="images/placeholder.svg" alt="朗读" width="16" height="16">
                                朗读
                            </button>
                        </div>
                    </div>
                    <div id="result-text" class="result-text"></div>
                </div>
            </div>
            
            <div class="contextual-translation">
                <h2>情境化翻译</h2>
                <p>提供使用场景，获取更准确的翻译和文化背景信息</p>
                
                <div class="context-input">
                    <label for="context-text">使用场景描述</label>
                    <textarea id="context-text" placeholder="例如：在日本餐厅点餐时使用，需要礼貌地询问服务员"></textarea>
                    <button id="contextual-translate-btn" class="primary-btn">获取情境化翻译</button>
                </div>
                
                <div id="contextual-result" class="contextual-result" style="display: none;">
                    <h3>情境化翻译结果</h3>
                    
                    <div class="translation-types">
                        <div class="translation-type">
                            <h4>直译</h4>
                            <p id="literal-translation">这是直译的内容</p>
                        </div>
                        
                        <div class="translation-type">
                            <h4>情境化翻译</h4>
                            <p id="contextual-translation">这是考虑了文化背景和使用场景的翻译</p>
                        </div>
                        
                        <div class="translation-type">
                            <h4>替代表达</h4>
                            <div class="alternatives">
                                <h5>更地道的表达方式</h5>
                                <div id="alternative-list" class="alternative-list">
                                    <span class="alternative-item">替代表达1</span>
                                    <span class="alternative-item">替代表达2</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="translation-type">
                            <h4>文化注释</h4>
                            <div id="cultural-notes" class="cultural-notes">
                                <h5>文化背景</h5>
                                <p>这里是关于这个表达在目标语言文化中的使用背景和注意事项</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="history-section">
                <h2>翻译历史</h2>
                <div class="history-list">
                    <div class="history-item">
                        <div class="history-text">
                            <div class="original-text">Hello, how are you?</div>
                            <div class="translated-text">你好，你好吗？</div>
                        </div>
                        <div class="history-meta">
                            <div class="language-pair">英文 → 中文</div>
                            <div class="history-date">2025-05-20 14:30</div>
                        </div>
                    </div>
                    
                    <div class="history-item">
                        <div class="history-text">
                            <div class="original-text">Where is the nearest subway station?</div>
                            <div class="translated-text">最近的地铁站在哪里？</div>
                        </div>
                        <div class="history-meta">
                            <div class="language-pair">英文 → 中文</div>
                            <div class="history-date">2025-05-20 13:45</div>
                        </div>
                    </div>
                    
                    <div class="history-item">
                        <div class="history-text">
                            <div class="original-text">I would like to order this dish, please.</div>
                            <div class="translated-text">我想点这个菜，谢谢。</div>
                        </div>
                        <div class="history-meta">
                            <div class="language-pair">英文 → 中文</div>
                            <div class="history-date">2025-05-19 19:20</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <footer>
        <p>&copy; 2025 多语言旅行助手 | 版本 1.0</p>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const sourceText = document.getElementById('source-text');
            const translateBtn = document.getElementById('translate-btn');
            const clearBtn = document.getElementById('clear-btn');
            const voiceInputBtn = document.getElementById('voice-input-btn');
            const copyBtn = document.getElementById('copy-btn');
            const speakBtn = document.getElementById('speak-btn');
            const contextualTranslateBtn = document.getElementById('contextual-translate-btn');
            const characterCount = document.querySelector('.character-count');
            const translationResult = document.getElementById('translation-result');
            const resultText = document.getElementById('result-text');
            const contextualResult = document.getElementById('contextual-result');
            const swapLanguagesBtn = document.getElementById('swap-languages');
            const sourceLangSelect = document.getElementById('source-language');
            const targetLangSelect = document.getElementById('target-language');
            
            // 语言切换按钮
            swapLanguagesBtn.addEventListener('click', function() {
                // 不交换自动检测
                if (sourceLangSelect.value === 'auto') {
                    alert('自动检测语言无法交换');
                    return;
                }
                
                // 交换语言
                const sourceValue = sourceLangSelect.value;
                const targetValue = targetLangSelect.value;
                
                sourceLangSelect.value = targetValue;
                targetLangSelect.value = sourceValue;
                
                // 如果有文本和翻译结果，也交换它们
                if (resultText.textContent) {
                    const originalText = sourceText.value;
                    sourceText.value = resultText.textContent;
                    resultText.textContent = originalText;
                    characterCount.textContent = `${sourceText.value.length}/5000`;
                }
            });
            
            // 更新字符计数
            sourceText.addEventListener('input', function() {
                const count = this.value.length;
                characterCount.textContent = `${count}/5000`;
                
                // 如果超过限制，禁用输入
                if (count > 5000) {
                    this.value = this.value.substring(0, 5000);
                    characterCount.textContent = '5000/5000';
                }
            });
            
            // 翻译按钮
            translateBtn.addEventListener('click', async function() {
                const text = sourceText.value.trim();
                if (!text) return;
                
                const sourceLang = sourceLangSelect.value;
                const targetLang = targetLangSelect.value;
                
                // 显示加载状态
                translateBtn.disabled = true;
                translateBtn.textContent = '正在调用LLM大模型...';
                
                // 显示LLM调用状态
                const statusDiv = document.createElement('div');
                statusDiv.className = 'llm-status';
                statusDiv.innerHTML = '<div class="loading-spinner"></div><span>正在调用LLM大模型进行翻译...</span>';
                
                // 如果结果区域已显示，则添加状态信息
                if (translationResult.style.display === 'block') {
                    resultText.innerHTML = '';
                    resultText.appendChild(statusDiv);
                } else {
                    translationResult.style.display = 'block';
                    resultText.innerHTML = '';
                    resultText.appendChild(statusDiv);
                }
                
                try {
                    // 模拟调用LLM大模型翻译API
                    // 实际项目中应该替换为真实的API调用
                    const translatedText = await simulateLLMTranslation(text, sourceLang, targetLang);
                    
                    // 显示翻译结果，添加LLM标识
                    resultText.innerHTML = `
                        <div class="llm-badge">由LLM大模型提供翻译</div>
                        <div class="translation-content">${translatedText}</div>
                    `;
                    
                    // 保存到历史记录
                    saveToHistory(text, translatedText, sourceLang, targetLang);
                } catch (error) {
                    console.error('翻译错误:', error);
                    resultText.innerHTML = `<div class="error-message">翻译失败: ${error.message}</div>`;
                } finally {
                    translateBtn.disabled = false;
                    translateBtn.textContent = '翻译';
                }
            });
            
            // 真实调用LLM大模型翻译
            async function simulateLLMTranslation(text, sourceLang, targetLang) {
                try {
                    // 记录LLM调用信息到控制台，方便开发者确认
                    console.log('LLM大模型调用信息:', {
                        inputText: text,
                        sourceLang: sourceLang,
                        targetLang: targetLang,
                        timestamp: new Date().toISOString()
                    });
                    
                    // 调用后端API，连接到真实的LLM服务
                    const response = await fetch('/api/translate', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            text: text,
                            source_lang: sourceLang,
                            target_lang: targetLang
                        }),
                    });
                    
                    if (!response.ok) {
                        const errorData = await response.json();
                        throw new Error(errorData.error || '翻译服务出错');
                    }
                    
                    const data = await response.json();
                    
                    // 记录使用的模型信息
                    console.log('使用的LLM模型:', data.model_used);
                    
                    return data.translated_text;
                } catch (error) {
                    console.error('LLM模型调用错误:', error);
                    throw new Error('LLM翻译服务暂时不可用，请稍后再试');
                }
            }
            
            // 保存到历史记录
            function saveToHistory(originalText, translatedText, sourceLang, targetLang) {
                // 实际项目中应该保存到数据库或本地存储
                console.log('保存翻译历史:', {
                    originalText,
                    translatedText,
                    sourceLang,
                    targetLang,
                    timestamp: new Date()
                });
            }
            
            // 清空按钮
            clearBtn.addEventListener('click', function() {
                sourceText.value = '';
                characterCount.textContent = '0/5000';
                translationResult.style.display = 'none';
            });
            
            // 语音输入按钮
            voiceInputBtn.addEventListener('click', function() {
                if ('webkitSpeechRecognition' in window) {
                    const recognition = new webkitSpeechRecognition();
                    const sourceLang = sourceLangSelect.value;
                    
                    recognition.lang = sourceLang === 'auto' ? 'zh-CN' : sourceLang;
                    recognition.continuous = false;
                    recognition.interimResults = false;
                    
                    recognition.onstart = function() {
                        voiceInputBtn.textContent = '正在听...';
                        voiceInputBtn.disabled = true;
                    };
                    
                    recognition.onresult = function(event) {
                        const transcript = event.results[0][0].transcript;
                        sourceText.value = transcript;
                        characterCount.textContent = `${transcript.length}/5000`;
                    };
                    
                    recognition.onerror = function(event) {
                        console.error('语音识别错误:', event.error);
                        alert(`语音识别失败: ${event.error}`);
                    };
                    
                    recognition.onend = function() {
                        voiceInputBtn.innerHTML = '<img src="images/placeholder.svg" alt="语音输入" width="16" height="16"> 语音输入';
                        voiceInputBtn.disabled = false;
                    };
                    
                    recognition.start();
                } else {
                    alert('您的浏览器不支持语音识别功能');
                }
            });
            
            // 复制按钮
            copyBtn.addEventListener('click', function() {
                // 获取翻译内容，排除LLM标识
                const translationContent = document.querySelector('.translation-content');
                const text = translationContent ? translationContent.textContent : resultText.textContent;
                
                navigator.clipboard.writeText(text).then(() => {
                    const originalText = copyBtn.innerHTML;
                    copyBtn.textContent = '已复制';
                    setTimeout(() => {
                        copyBtn.innerHTML = originalText;
                    }, 2000);
                }).catch(err => {
                    console.error('复制失败:', err);
                    alert('复制失败，请手动复制');
                });
            });
            
            // 朗读按钮
            speakBtn.addEventListener('click', function() {
                const text = resultText.textContent;
                const targetLang = targetLangSelect.value;
                speakText(text, targetLang);
            });
            
            // 情境化翻译按钮
            contextualTranslateBtn.addEventListener('click', async function() {
                const text = sourceText.value.trim();
                if (!text) {
                    alert('请先输入要翻译的文本');
                    return;
                }
                
                const context = document.getElementById('context-text').value.trim();
                if (!context) {
                    alert('请描述使用场景');
                    return;
                }
                
                const sourceLang = sourceLangSelect.value;
                const targetLang = targetLangSelect.value;
                
                // 显示加载状态
                contextualTranslateBtn.disabled = true;
                contextualTranslateBtn.textContent = '调用LLM大模型中...';
                
                // 显示加载状态
                const loadingDiv = document.createElement('div');
                loadingDiv.className = 'llm-status';
                loadingDiv.innerHTML = '<div class="loading-spinner"></div><span>正在调用LLM大模型进行情境化翻译...</span>';
                
                // 如果结果区域已显示，则添加状态信息
                if (contextualResult.style.display === 'block') {
                    document.getElementById('literal-translation').innerHTML = '';
                    document.getElementById('contextual-translation').innerHTML = '';
                    document.getElementById('alternative-list').innerHTML = '';
                    document.getElementById('cultural-notes').querySelector('p').innerHTML = '';
                    document.getElementById('literal-translation').appendChild(loadingDiv.cloneNode(true));
                } else {
                    contextualResult.style.display = 'block';
                    document.getElementById('literal-translation').innerHTML = '';
                    document.getElementById('literal-translation').appendChild(loadingDiv);
                }
                
                try {
                    // 调用后端API进行情境化翻译
                    const response = await fetch('/api/translate/contextual', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            text: text,
                            context: context,
                            source_lang: sourceLang,
                            target_lang: targetLang
                        }),
                    });
                    
                    if (!response.ok) {
                        const errorData = await response.json();
                        throw new Error(errorData.error || '情境化翻译服务出错');
                    }
                    
                    const data = await response.json();
                    
                    // 记录使用的模型信息
                    console.log('使用的LLM模型:', data.model_used);
                    
                    // 显示情境化翻译结果
                    document.getElementById('literal-translation').innerHTML = `
                        <div class="llm-badge">由LLM大模型提供</div>
                        <div class="translation-content">${data.translations.literal}</div>
                    `;
                    
                    document.getElementById('contextual-translation').innerHTML = `
                        <div class="llm-badge">由LLM大模型提供</div>
                        <div class="translation-content">${data.translations.contextual}</div>
                    `;
                    
                    // 更新替代表达
                    const alternativeList = document.getElementById('alternative-list');
                    alternativeList.innerHTML = '<div class="llm-badge">由LLM大模型提供</div>';
                    data.translations.alternatives.forEach(alt => {
                        const span = document.createElement('span');
                        span.className = 'alternative-item';
                        span.textContent = alt;
                        alternativeList.appendChild(span);
                    });
                    
                    // 更新文化注释
                    const culturalNotes = document.getElementById('cultural-notes');
                    culturalNotes.querySelector('p').innerHTML = `
                        <div class="llm-badge">由LLM大模型提供</div>
                        <div class="translation-content">${data.translations.cultural_notes}</div>
                    `;
                    
                    // 显示结果
                    contextualResult.style.display = 'block';
                } catch (error) {
                    console.error('情境化翻译错误:', error);
                    document.getElementById('literal-translation').innerHTML = `<div class="error-message">情境化翻译失败: ${error.message}</div>`;
                    document.getElementById('contextual-translation').innerHTML = '';
                    document.getElementById('alternative-list').innerHTML = '';
                    document.getElementById('cultural-notes').querySelector('p').innerHTML = '';
                } finally {
                    contextualTranslateBtn.disabled = false;
                    contextualTranslateBtn.textContent = '获取情境化翻译';
                }
            });
            
            // 翻译历史项点击
            document.querySelectorAll('.history-item').forEach(item => {
                item.addEventListener('click', function() {
                    const originalText = this.querySelector('.original-text').textContent;
                    sourceText.value = originalText;
                    characterCount.textContent = `${originalText.length}/5000`;
                    
                    // 自动滚动到顶部
                    window.scrollTo({
                        top: 0,
                        behavior: 'smooth'
                    });
                });
            });
        });
        
        // 文本朗读
        function speakText(text, lang) {
            if ('speechSynthesis' in window) {
                const utterance = new SpeechSynthesisUtterance(text);
                utterance.lang = lang;
                window.speechSynthesis.speak(utterance);
            } else {
                console.log('浏览器不支持语音合成');
            }
        }
    </script>
</body>
</html>